package com.egghiro.framework.j2se.game.controller.action;

import com.egghiro.framework.j2se.game.core.SMath;
import com.egghiro.framework.j2se.game.core.model.actor.IActor2D;
import com.egghiro.framework.j2se.game.model.element.LinearVelocity2D;
import com.egghiro.framework.j2se.game.model.shape.SVector2D;

public class RightAngleTrajectoryCorrection extends TrajectoryCorrectionAction {
    private final double MAX_ANGLE;
    private IActor2D homingMissile;

    public RightAngleTrajectoryCorrection(IActor2D homingMissile, double maxAngle) {
        this.homingMissile = homingMissile;
        if (maxAngle < 0) {
            maxAngle = 0;
        } else if (maxAngle > 180) {
            maxAngle = 180;
        }
        MAX_ANGLE = maxAngle;
    }

    @Override
    public void trajectoryCorrrection(IActor2D target, LinearVelocity2D speed) {
        SVector2D vector = new SVector2D(target.getCollidePointX()
                - homingMissile.getCollidePointX(), target.getCollidePointY()
                - homingMissile.getCollidePointY());
        double alpha = speed.getAngleInDigree();
        double beta = SMath.vectorToDigree(vector);
        while (beta > alpha) {
            beta -= 360;
        }
        double omiga = alpha - beta;
        if (0 < omiga && omiga <= MAX_ANGLE) {
            speed.turn(-omiga);
        } else if (MAX_ANGLE < omiga && omiga <= 180) {
            speed.turn(-MAX_ANGLE);
        } else if (180 < omiga && omiga <= (360 - MAX_ANGLE)) {
            speed.turn(MAX_ANGLE);
        } else if ((360 - MAX_ANGLE) < omiga && omiga < 360) {
            speed.turn(360 - omiga);
        }
    }
}
